from rest_framework import serializers
from book.models import BookInfo


class HeroInfoSerialzier(serializers.Serializer):
    # 英雄序列化器
    hname = serializers.CharField()
    hcomment = serializers.CharField()
    # hbook=serializers.PrimaryKeyRelatedField()
    hbook = serializers.StringRelatedField()


# 自定义序列化器
class BookSerializer(serializers.Serializer):
    """
    序列返回字段
    """
    btitle = serializers.CharField(max_length=20, min_length=2, write_only=True)
    bread = serializers.IntegerField(max_value=100, min_value=5)
    bpub_date = serializers.DateField()
    bcomment = serializers.IntegerField(default=10)
    # 1.返回关联的英雄id   PrimaryKeyRelatedField
    # heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True,many=True)
    # 2.返回关联英雄模型类的str方法值
    heroinfo_set = serializers.StringRelatedField(read_only=True, many=True)
    # 3.返回关联英雄的自定义信息
    # heroinfo_set = HeroInfoSerialzier(many=True)

    # 单一字段验证
    def validate_btitle(self, value):

        if value == 'python':
            # print('书名不能时python')
            raise serializers.ValidationError('书名不能时python')
        return value

    # 多个字段验证
    def validate(self, attrs):

        if attrs['bread'] < attrs['bcomment']:
            raise serializers.ValidationError('阅读量大于评论量')

        return attrs

    def create(self, validated_data):
        # 保存数据 ser.save()
        book = BookInfo.objects.create(**validated_data)

        return book

    def update(self, instance, validated_data):
        # 更新数据
        instance.btitle = validated_data['btitle']
        instance.bread = validated_data['bread']
        instance.save()
        return instance

#
# class BookSerializer(serializers.ModelSerializer):
#     """
#     模型类序列化器的使用，
#     """
#     class Meta:
#         model = BookInfo  # 指定生成字段的模型类
#         fields=('btitle','bread')  # 指定模型类中的字段
#         read_only_fields=('btitle',)
#         # exclude=('btitle',)
#         # 添加修改字段选项参数
#         # extra_kwargs={
#         #     "bcomment":{
#         #         'max_value':100
#         #     },
#         #     'btitle':{
#         #         'min_length':5
#         #     }
#         #
#         # }